package com.atguigu.yygh.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.yygh.common.handler.YyghException;
import com.atguigu.yygh.oss.Utils.ConstantPropertiesUtil;
import com.atguigu.yygh.oss.service.FileService;
import org.joda.time.DateTime;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl  implements FileService {

    //上传文件
    @Override
    public String upload(MultipartFile file) {
        //1准备参数
// yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String endpoint = ConstantPropertiesUtil.END_POINT;
// 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;
        //2创建客户端
        OSS ossClient =
                new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
        try {
            //3 调用客户端方法上传文件
            InputStream inputStream = file.getInputStream();
            String fileName  = file.getOriginalFilename();
            //UUID+01.jpg
            String uuidUrl = UUID.randomUUID().toString().replace("-","");
            fileName = uuidUrl+fileName;
            //创建目录 2021/12/11/UUID+01.jpg
            String timeUrl = new DateTime().toString("yyyy/MM/dd");
            fileName = timeUrl+"/"+fileName;
            ossClient.putObject(bucketName,fileName,inputStream);
            //4 关闭客户端
            ossClient.shutdown();
            //5 返回url
            //https://guli-file210712java.oss-cn-beijing.aliyuncs.com/02.jpg
            String url = "https://"+bucketName
                    +"."+endpoint+"/"+fileName;

            return url;
        } catch (IOException e) {
            e.printStackTrace();
            throw  new YyghException(20001,"上传文件失败");
        }
    }

}
